package com.greatwqs.wmall.user.provider.service.impl;

import com.greatwqs.wmall.common.module.exception.AppException;
import com.greatwqs.wmall.common.module.exception.ErrorCode;
import com.greatwqs.wmall.common.provider.cache.CacheNames;
import com.greatwqs.wmall.common.module.util.JsonUtil;
import com.greatwqs.wmall.user.provider.manager.UserManager;
import com.greatwqs.wmall.user.provider.mapper.UserMapper;
import com.greatwqs.wmall.user.provider.model.dto.ChangePasswordDto;
import com.greatwqs.wmall.user.provider.model.dto.UserRegisterDto;
import com.greatwqs.wmall.user.provider.model.po.User;
import com.greatwqs.wmall.user.provider.model.vo.UserVo;
import com.greatwqs.wmall.user.provider.service.UserService;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author wang-qingsong
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserManager userManager;

    @Override
    @Transactional
    public Long register(UserRegisterDto registerDto) {
        User userExist = userManager.getPoByLoginId(registerDto.getLoginId());
        if (userExist != null) {
            log.warn("user not exist, registerDto: " + JsonUtil.toJson(registerDto));
            throw new AppException(ErrorCode.USER_LOGIN_ID_ALREADY_EXIST);
        }

        User insert = User.register(registerDto);
        userMapper.insert(insert);
        return insert.getUserId();
    }

    @Override
    // @Cacheable(cacheNames = CacheNames.USER, key = "#userId", sync = true)
    public UserVo getUserVo(Long userId) {
        User userExist = userManager.getPoNotNull(userId);
        return new UserVo(userExist);
    }

    /**
     * 修改密码
     *
     * @param userDto
     */
    @Override
    @Transactional
    @CacheEvict(cacheNames = CacheNames.USER, key = "#userDto.userId")
    public void changePassword(ChangePasswordDto userDto) {
        User exist = userManager.getPo(userDto.getUserId());
        if (exist == null) {
            log.warn("user not exist! userDto: " + JsonUtil.toJson(userDto));
            throw new AppException(ErrorCode.USER_NOT_FOUND);
        }

        if (!StringUtils.equals(exist.getUserPwd(), userDto.getOldPassword())) {
            log.warn("oldPassword not matched the DB password! userDto: " + JsonUtil.toJson(userDto));
            throw new AppException((ErrorCode.USER_LOGIN_PASSWORD_ERROR));
        }

        exist.setUserPwd(userDto.getNewPassword());
        exist.setUpdateTime(new Date());
        userMapper.updateUserPwdByUserId(exist);
    }
}
